package com.imy.virtual.client.hook.delegate;

import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.imy.virtual.VClientImpl;
import com.imy.virtual.client.core.VirtualCore;
import com.imy.virtual.client.fixer.ActivityFixer;
import com.imy.virtual.client.fixer.ContextFixer;
import com.imy.virtual.client.hook.controller.IVirtualController;
import com.imy.virtual.client.interfaces.IInjector;
import com.imy.virtual.client.ipc.ActivityClientRecord;
import com.imy.virtual.client.ipc.VActivityManager;
import com.imy.virtual.helper.compat.BundleCompat;
import com.imy.virtual.helper.utils.VLog;
import com.imy.virtual.os.VUserHandle;
import com.imy.virtual.server.interfaces.IUiCallback;

import mirror.android.app.ActivityThread;
import mirror.dalvik.system.VMRuntime;

public final class AppInstrumentation extends InstrumentationDelegate implements IInjector {
    private static final String TAG = AppInstrumentation.class.getSimpleName();
    private static AppInstrumentation gDefault;
    private Handler mHandler =new Handler(Looper.getMainLooper());
    private AppInstrumentation(Instrumentation base) {
        super(base);
        VLog.i("每初始化一个进程，那么这里将都创建一个 AppInstrumentation ");
    }

    public static AppInstrumentation getDefault() {
        if (gDefault == null) {
            synchronized (AppInstrumentation.class) {
                if (gDefault == null) {
                    gDefault = create();
                }
            }
        }
        return gDefault;
    }

    private static AppInstrumentation create() {
        Instrumentation instrumentation = ActivityThread.mInstrumentation.get(VirtualCore.mainThread());
        VLog.i(" 当前创建 AppInstrumentation ， 查看通过 ActivityThread.mInstrumentation 创建的是否是 AppInstrumentation， 判断 = " + (instrumentation instanceof AppInstrumentation));
        if (instrumentation instanceof AppInstrumentation) {
            return (AppInstrumentation) instrumentation;
        }
        return new AppInstrumentation(instrumentation);
    }

    @Override
    public void inject() throws Throwable {
        base = ActivityThread.mInstrumentation.get(VirtualCore.mainThread());
        Log.i(TAG, "inject:" + base);
        ActivityThread.mInstrumentation.set(VirtualCore.mainThread(), this);
        Instrumentation instrumentation = ActivityThread.mInstrumentation.get(VirtualCore.mainThread());

        boolean envBad = isEnvBad();
        Log.i(TAG, "inject after:" + instrumentation + " envBad:" + envBad + " 进程：" + VirtualCore.get().getProcessName());
    }

    @Override
    public boolean isEnvBad() {
        return !(ActivityThread.mInstrumentation.get(VirtualCore.mainThread()) instanceof AppInstrumentation);
    }

    @Override
    public void callActivityOnCreate(final Activity activity, Bundle icicle) {

        //Log.i(TAG,"当前运行在64虚拟机："+ VMRuntime.is64Bit.call(VMRuntime.getRuntime.call())
        //+"进程:"+ VirtualCore.get().getProcessName());
        Log.i(TAG, "callActivityOnCreate activity:" + activity.getClass().getName());
        if (icicle != null) {
            BundleCompat.clearParcelledData(icicle);
        }

        VirtualCore.get().getComponentDelegate().beforeActivityCreate(activity);
        IBinder token = mirror.android.app.Activity.mToken.get(activity);
        ActivityClientRecord r = VActivityManager.get().getActivityRecord(token);
        if (r != null) {
            IVirtualController virtualController = VirtualCore.get().getVirtualController();
            if (virtualController != null) {
                virtualController.controllerActivityCreate(activity);
            }
            r.activity = activity;
        }
        ContextFixer.fixContext(activity);
        ActivityFixer.fixActivity(activity);
        ActivityInfo info = null;
        if (r != null) {
            info = r.info;
        }
        if (info != null) {
            if (info.theme != 0) {
                activity.setTheme(info.theme);
            }
            if (activity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
                    && info.screenOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
                activity.setRequestedOrientation(info.screenOrientation);
            }
        }
        super.callActivityOnCreate(activity, icicle);
        VirtualCore.get().getComponentDelegate().afterActivityCreate(activity);


    }

    private void getAllView(final ViewGroup viewGroup) {


                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    View childAt = viewGroup.getChildAt(i);
                    if (childAt instanceof ViewGroup){
                        getAllView((ViewGroup) childAt);
                    }else {
                        childAt.toString();
                        Log.i(TAG,"getAllView:"+childAt);
                    }
                }

    }

    @Override
    public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {
        if (icicle != null) {
            BundleCompat.clearParcelledData(icicle);
        }
        callActivityOnCreate(activity, icicle);

//        super.callActivityOnCreate(activity, icicle, persistentState);
    }

    @Override
    public void callActivityOnResume(Activity activity) {
        Log.i(TAG, "callActivityOnResume activity:" + activity.getClass().getName());

        VirtualCore.get().getComponentDelegate().beforeActivityResume(activity);
        IVirtualController virtualController = VirtualCore.get().getVirtualController();
        if (virtualController != null) {
            virtualController.controllerActivityResume(activity);
        }
        VActivityManager.get().onActivityResumed(activity);
        super.callActivityOnResume(activity);
        VirtualCore.get().getComponentDelegate().afterActivityResume(activity);
        //
        final View viewById = activity.findViewById(android.R.id.content);
       if (viewById instanceof ViewGroup){
           mHandler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   getAllView((ViewGroup) viewById);
               }
           },5000);

       }
        Intent intent = activity.getIntent();
        if (intent != null) {
            Bundle bundle = intent.getBundleExtra("_VA_|_sender_");
            if (bundle != null) {
                IBinder callbackToken = BundleCompat.getBinder(bundle, "_VA_|_ui_callback_");
                IUiCallback callback = IUiCallback.Stub.asInterface(callbackToken);
                if (callback != null) {
                    try {
                        callback.onAppOpened(VClientImpl.get().getCurrentPackage(), VUserHandle.myUserId());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void callActivityOnDestroy(Activity activity) {
        VirtualCore.get().getComponentDelegate().beforeActivityDestroy(activity);
        IVirtualController virtualController = VirtualCore.get().getVirtualController();
        if (virtualController != null) {
            virtualController.controllerActivityDestroy(activity);
        }
        Log.i(TAG, " callActivityOnDestroy activity:" + activity.getClass().getName());
        VActivityManager.get().onActivityDestroy(activity);
        super.callActivityOnDestroy(activity);
        VirtualCore.get().getComponentDelegate().afterActivityDestroy(activity);
    }

    @Override
    public void callActivityOnPause(Activity activity) {
        IVirtualController virtualController = VirtualCore.get().getVirtualController();
        if (virtualController != null) {
            virtualController.controllerActivityPause(activity);
        }
        VirtualCore.get().getComponentDelegate().beforeActivityPause(activity);
        super.callActivityOnPause(activity);
        VirtualCore.get().getComponentDelegate().afterActivityPause(activity);
    }

    @Override
    public void callApplicationOnCreate(Application app) {
        super.callApplicationOnCreate(app);
    }
}
